<template>
  <div>
    <header-tilte :title="title"></header-tilte>
    <div class="flex_center">
      <div class="bodyContent" style="overflow: hidden;overflow-y: auto">
        <loading v-if="showLoading"></loading>
        <div v-if="!showLoading">
          <div class="white_bac">
            <div class="waterChooseContent flex">
              <img :src="waterBillChoosed.goods_img">
              <div>
                <p>{{waterBillChoosed.goods_name}}</p>
                <p style="text-decoration:line-through;color: #ef1336">价格：{{waterBillChoosed.goods_price}}/桶</p>
                <p>水票价：<span class="font-weight" style="color: #ef1336">￥{{waterBillChoosed.goods_price * categoryChoosed.buy_num}}/{{categoryChoosed.total_num}}</span> 桶</p>

              </div>
            </div>
          </div>
          <pay-type-choose v-on:radioValue="radioValue"></pay-type-choose>
          <div class="white_bac margin_top">
            <div style="padding: 1rem;text-align: left">
              <p>已选套餐：{{categoryChoosed.title}}</p>
              <p v-if="categoryChoosed.description != undefined && categoryChoosed.description != null && categoryChoosed.description != ''">优惠活动：{{categoryChoosed.description}}</p>
              <p style="color: #ef1336;text-align: right">实付：<span >￥<span class="font-weight" style="font-size: 1.2rem">{{waterBillChoosed.goods_price * categoryChoosed.buy_num}}</span></span></p>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="bookingButton positon_fix" @click="sureOrder">
      <mu-button color="error">确定订单</mu-button>
    </div>
  </div>
</template>

<script>
    import HeaderTilte from "../../../components/headerTilte";
    import Loading from "../../../components/loading";
    import PayTypeChoose from "../../../components/components/PayTypeChoose"
    export default {
      data(){
        return{
          showLoading:true,
          title:'水票订单',
          waterBillChoosed:'',
          tabs: ["微信支付",'货到付款'],
          radio: 0,//0微信 1：货到
          categoryChoosed:'',
          cacheName:'',
          url:''
        }
      },
      mounted(){
        this.checkLogin();
        this.initH();
        this.$nextTick(function () {
          $('.mu-radio-label').css('font-size','14px')
        })
        this.waterBillChoosed = this.getCache('chooseTickt');
        if(this.isEmpty(this.waterBillChoosed)){
          this.$toast.warning('已付款订单');
          var _self = this;
          setTimeout(function () {
            _self.$router.push({path:'/qds/waterbilllist'})
          },1000)
          return;
        }
        var index = this.waterBillChoosed.chooseNum;
        this.categoryChoosed = this.waterBillChoosed.waterbill_category[index];

        var login_key = this.getCache('login_key');
        this.cacheName = login_key.mid + "_" + login_key.sid + '_' + 'order';
      },
      methods:{
        initH(){
          var allH = document.documentElement.clientHeight;
          var headerH = $('.header').height();
          var footH = $('.bookingButton').height();
          var h = allH - headerH -footH;
          $('.bodyContent').css('height',h + 'px');
          this.showLoading = false
        },
        sureOrder(){
          this.url = '/waterbill/pay'
          if(this.radio == 1){ //表示货到付款
            this.url = '/waterbill/add'
          }
          //判断是否是首次购水
          this.isFirstBookingWater();
        },
        isFirstBookingWater(){
          var showComfrim = 0;
          if(this.getCache(this.cacheName) == 1){
            showComfrim = 1;
            this.sureBuy(showComfrim);
          }else {
            this.yesS.getOrderList(
              this.$combineParams({type: 1})
            ).then(res => {
              var status = res.status;
              if(status == 1){
                var list = res.data.order_list.data;
                var count = 0;
                this.setCache(this.cacheName, 0);
                if (!this.isEmpty(list) && list.length > 0) {
                  for (var i = 0; i < list.length; i++) {
                    if (list[i].status == 20) {
                      count++;
                      break
                    }
                  }
                }
                if (count > 0) {
                  this.setCache(this.cacheName, 1);
                  showComfrim = 1
                }
                this.sureBuy(showComfrim);
              }
            })
          }
        },
        sureBuy(type){
          if(type == 0){
            this.$alert('首次订水，需付桶押金，送水工线下收取，押金可退。', '提示', {
              type: 'warning'
            }).then(({ result }) => {
              if (result) {
                this.buyEnd();
              }
            });
          }else {
            this.buyEnd();
          }
        },
        buyEnd(){
          console.log(this.url);
          this.$axios.post(this.url,this.$combineParams({
            bill_id: this.categoryChoosed.id,
            waterbill_id: this.waterBillChoosed.id,
            type:this.radio
          })).then(res => {
            var status = res.data.status;
            if(status == 1){
              if (this.url.indexOf('waterbill/add') != -1) { //表示是货到付款
                //如果是货到付款，跳转到支付成功页面
                this.$router.push({path:'/qds/Success',query:{toType:2}})
              } else {
                //微信支付

                this.payment(res.data);
              }
            }else {
              this.$toast.error(res.data.msg);
            }

          }).catch(res => {
            this.$toast.error("支付失败，请稍后再试");
          })
        },

        //微信支付
        payment(data) {

            this.wxPay(data, 2);

        },
        isPaySuccess(data){
          this.yesS.isPaySuccess(
            this.$combineParams({id:data.id})
          ).then(res => {
            var status = 0;
            if (res.data.result != undefined) {
              status = res.data.result;
            }
            if (status) {
              this.$router.push({path:'/qds/success',query:{toType:2}});
            } else {
              this.$router.push({path:'/qds/fail',query:{toType:1}});
            }
          }).catch(res => {
            this.$toast.error('支付失败，请稍后再试')
          })
        },
        radioValue: function (childValue) {
          this.radio = childValue;
        },
        //微信支付
        /*wxPay (params, type) {
          function onBridgeReady() {
            if (typeof WeixinJSBridge === 'undefined') {
              malert('请在微信在打开页面！');
              return false;
            }
            WeixinJSBridge.invoke(
              'getBrandWCPayRequest', {
                "appId": params.appId,     //公众号名称，由商户传入
                "timeStamp": params.timeStamp,         //时间戳，自1970年以来的秒数
                "nonceStr": params.nonceStr, //随机串
                "package": params.package,
                "signType": params.signType,         //微信签名方式：
                "paySign": params.paySign //微信签名
              },
              function (res) {
                switch (res.err_msg) {
                  case 'get_brand_wcpay_request:cancel':
                    malert('', '用户取消支付！', function () {
                      if (parseInt(type) == 1) {
                        /!*locationReplace('index.html');*!/
                        this.$router.push({path:'/goods'})
                      } else {
                        /!*locationReplace('water-ticket.html');*!/
                        this.$router.push({path:'/qds/bookingWater'});
                      }
                    });
                    break;
                  case 'get_brand_wcpay_request:fail':
                    this.$alert('支付失败', '提示', {
                      type: 'warning'
                    }).then(({ result }) => {
                      if (result) {
                        this.$router.push({path:'/qds/fail',query:{toType:1}});
                      }
                    });
                    /!*malert(res.err_desc, '支付失败', function () {
                      locationReplace('fail.html?type=1');
                    });*!/
                    break;
                  case 'get_brand_wcpay_request:ok':
                    this.$router.push({path:'/qds/success',query:{toType:type}});
                    /!*locationReplace('success.html?type=' + type);*!/
                    break;
                  default:
                    alert(JSON.stringify(res));
                    break;
                }
              });
          }

          if (typeof WeixinJSBridge == "undefined") {
            if (document.addEventListener) {
              document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
            } else if (document.attachEvent) {
              document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
              document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
            }
          } else {
            onBridgeReady();
          }
        },*/
      },
      components: {
        Loading,
        HeaderTilte,
        PayTypeChoose},
      name: "water-bill-order"
    }
</script>

<style scoped>
  /*@import 'http://cdn.bootcss.com/material-design-icons/3.0.1/iconfont/material-icons.css';*/
  .bookingButton{
    left: 0;
    right: 0;
    bottom: 0;
  }
  .bookingButton button{
    width: 100% !important;
    height: 45px!important;
    line-height: 45px!important;

  }
  .margin_top {
    margin-top: 0.5rem;
  }
  .payTypeTitle img{
    width: 1rem;
    height: 1rem;
  }
  .margin_right {
    margin-right: 0.2rem;
  }
  .mu-radio {
    margin-left: 0.5rem;
  }

  .waterChooseContent{
    padding: 1rem;
  }
  .waterChooseContent img{
    width: 5rem;
    height: 5rem;
    margin-right: 0.5rem;
  }
  .waterChooseContent p{
    text-align: left;
  }
</style>
